package com.turman.common.net

import com.turman.common.net.config.KtHttpLogInterceptor
import com.turman.common.net.config.LocalCookieJar
import com.turman.common.net.support.LiveDataCallAdapterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * retrofit封装类
 */
object KtRetrofit {
    private val mOkClient:OkHttpClient = OkHttpClient.Builder()
        .callTimeout(10, TimeUnit.SECONDS)
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .followRedirects(false)  //不支持重定向
//        .cache(Cache(File("sdcard/cache","okhttp"),1024))  //cache设置
//        .cookieJar(CookieJar.NO_COOKIES)
        .cookieJar(LocalCookieJar())  //cookie缓存策略
        .addNetworkInterceptor(KtHttpLogInterceptor{
            logLevel(KtHttpLogInterceptor.LogLevel.BODY)
        })
        .build()

    private val retrofitBuilder:Retrofit.Builder = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(LiveDataCallAdapterFactory())
        .client(mOkClient)

    private var retrofit:Retrofit? = null //retrofit请求client

    /**
     * 初始化配置
     */
    fun initConfig(baseUrl:String, okClient:OkHttpClient= mOkClient): KtRetrofit {
        retrofit = retrofitBuilder.baseUrl(baseUrl).client(okClient).build()
        return this
    }

    fun <T> getService(serviceClazz:Class<T>):T {
        if (retrofit ==null) {
            throw UninitializedPropertyAccessException("Retrofit必须初始化，需要配置baseUrl")
        } else {
            return retrofit!!.create(serviceClazz)
        }
    }

}